VTUtilJS = (function($) {
	var _TF_A_Z = 1;//kieu text
	var _TF_NUMBER = 2;//kieu integer
	var _TF_NUMBER_DOT = 3;//kieu float
	var _TF_NUMBER_COMMA = 4;//kieu so co dau ,
	var _TF_NUMBER_SIGN = 5;//kieu so co dau +-
	var _TF_NUMBER_CONVFACT = 7;//kieu convfact 23/3, /3, 0/3
	var keyCodes = {
		ENTER: 13, 
		BACK_SPACE: 8, 
		DELETE: 46, 
		TAB: 9, 
		F5: 116, 
		ESCAPE: 27, 
		CTRL:17, 
		SHIFT:16, 
		HOME:36, 
		END:35, 
		ARROW_LEFT:37, 
		ARROW_RIGHT:39, 
		ARROW_UP:38, 
		ARROW_DOWN:40
	};
	var Utils = {
		_CODE: 1,
		_NAME: 2,
		_ADDRESS: 3,
		_CTRL_PRESS: false,
		_SHIFT_PRESS: false,
		_TF_A_Z: 1,
		_TF_NUMBER: 2,
		_TF_NUMBER_DOT: 3,
		_TF_NUMBER_COMMA: 4,
		_TF_NUMBER_SIGN: 5,
		_TF_BAN_CHAR: 6,
		_TF_NUMBER_CONVFACT: 7,
		_TF_NUMBER_COMMA_AND_DOT: 8,
		_DATE_DD_MM_YYYY: 9,
		_DATE_MM_YYYY:10,
		_TF_CAR_NUMBER: 11,
		_NUMBER_TYPE:1,
		_STRING_TYPE:2,
		_DATE_TYPE:3,
		_PAYROLL:12
	};
	
	var fromKeyCode = function(n) {
		if( 47<=n && n<=90 ) return unescape('%'+(n).toString(16));
		if( 96<=n && n<=105) return 'NUM '+(n-96);
		if(112<=n && n<=135) return 'F'+(n-111);
		if(n==3)  return 'Cancel';
		if(n==6)  return 'Help';
		if(n==8)  return 'Backspace';
		if(n==9)  return 'Tab';
		if(n==12) return 'NUM 5';
		if(n==13) return 'Enter';
		if(n==16) return 'Shift';
		if(n==17) return 'Ctrl';
		if(n==18) return 'Alt';
		if(n==19) return 'Pause|Break';
		if(n==20) return 'CapsLock';
		if(n==27) return 'Esc';
		if(n==32) return 'Space';
		if(n==33) return 'PageUp';
		if(n==34) return 'PageDown';
		if(n==35) return 'End';
		if(n==36) return 'Home';
		if(n==37) return 'Left Arrow';
		if(n==38) return 'Up Arrow';
		if(n==39) return 'Right Arrow';
		if(n==40) return 'Down Arrow';
		if(n==42) return '*';
		if(n==43) return '+';
		if(n==44) return 'PrntScrn';
		if(n==45) return 'Insert';
		if(n==46) return 'Delete';
		if(n==91) return 'WIN Start';
		if(n==92) return 'WIN Start Right';
		if(n==93) return 'WIN Menu';
		if(n==106) return '*';
		if(n==107) return '+';
		if(n==108) return 'Separator';
		if(n==109) return '-';
		if(n==110) return '.';
		if(n==111) return '/';
		if(n==144) return 'NumLock';
		if(n==145) return 'ScrollLock';
		if(n==173) return 'Media Mute On|Off';
		if(n==174) return 'Media Volume Down';
		if(n==175) return 'Media Volume Up';
		if(n==176) return 'Media >>';
		if(n==177) return 'Media <<';
		if(n==178) return 'Media Stop';
		if(n==179) return 'Media Pause|Resume';
		if(n==182) return 'WIN My Computer';
		if(n==183) return 'WIN Calculator';
		if(n==186) return '; :';
		if(n==187) return '= +';
		if(n==188) return ', <';
		if(n==189) return '- _';
		if(n==190) return '. >';
		if(n==191) return '/ ?';
		if(n==192) return '\` ~';
		if(n==219) return '[ {';
		if(n==220) return '\\ |';
		if(n==221) return '] }';
		if(n==222) return '\' "';
		if(n==224) return 'META|Command';
		if(n==229) return 'WIN IME';
		if(n==255) return 'Device-specific';
		return null;
	};
	
	var bindFormatOnTextfield = function(obj, formatType){
		var reg = /[^0-9]/;
		var regAll = /[^0-9]/g;
		switch (formatType) {
		case _TF_A_Z:
			reg = /[^A-Z]/;
			regAll = /[^A-Za-z]/g; 
			break;
		case _TF_NUMBER_DOT:
			reg = /[^0-9.]/;
			regAll = /[^0-9.]/g; 
			break;
		case _TF_NUMBER:
			reg = /[^0-9]/;
			regAll = /[^0-9]/g; 
			break;
		case _TF_NUMBER_COMMA:
			reg = /[^0-9,]/;
			regAll = /[^0-9,]/g; 
			break;
		case _TF_NUMBER_SIGN:
			reg = /[^0-9-]/;
			regAll = /[^0-9-]/g; 
			break;
		case _TF_NUMBER_CONVFACT:
			reg = /[^0-9\/]/;
			regAll = /[^0-9\/]/g; 
			break;
		default:
			break;
		}
		if(typeof obj === 'string') {
			obj = $('#'+obj);
		}
		obj.bind('keyup', function(e){
			var code;
			if (!e) var e = window.event;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			if(code == keyCodes.CTRL){
				Utils._CTRL_PRESS = false;
			}
			if(code == keyCodes.SHIFT) {
				Utils._SHIFT_PRESS = false;
			}
		});
		obj.bind('keydown', function(e){
			var code;
			if (!e) var e = window.event;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = fromKeyCode(code).split(' ')[0];			
			if ((code >=96 && code <= 105) || (code>=48 && code<=57) || code==null || code==0 || code== keyCodes.BACK_SPACE || 
					code == keyCodes.TAB || code==keyCodes.ENTER || code==keyCodes.ESCAPE || code == keyCodes.DELETE ||
					(Utils._SHIFT_PRESS && code == keyCodes.HOME) || code == keyCodes.SHIFT || code == keyCodes.HOME || code == keyCodes.END ||
					code==keyCodes.CTRL || code == keyCodes.ARROW_LEFT || code == keyCodes.ARROW_RIGHT || code == keyCodes.ARROW_UP || code == keyCodes.ARROW_DOWN ||
					(Utils._CTRL_PRESS && (character  == 'v' || character  == 'V'))){
				if(code == keyCodes.CTRL){
					Utils._CTRL_PRESS = true;
				}
				if(code == keyCodes.SHIFT) {
					Utils._SHIFT_PRESS = true;
				}
				return true;
			} else if (reg.test(character) || (Utils._SHIFT_PRESS && !/[^0-9]/.test(character))) {
				return false;
			}else{
				return true;
			}
		});
		obj.bind('paste', function(){			
			var tmAZ = setTimeout(function(){
				obj.val(obj.val().replace(regAll,''));
				clearTimeout(tmAZ);
			},200);
		});
	};
	
	returnMoneyValue = function(valMoney) {
		var _valMoney = valMoney + '';
		var value = _valMoney.split(',').join('');
		var i=0;
		for(i=0;i<value.length-1;i++){// Nếu tất cả từ 0 -> length-2 là 0 thì
										// lấy số cuối
			if(value[i]!='0'){
				break;
			}
		}
		return value.substring(i,value.length);
	};
	
	formatCurrency = function(num) {
		if(num == undefined || num == null) {
			return '';
		}
		num = num.toString().split('.');
		var ints = num[0].split('').reverse();
		for (var out=[],len=ints.length,i=0; i < len; i++) {
			if (i > 0 && (i % 3) === 0){
				out.push(',');	
			}
			out.push(ints[i]);
		}
		out = out.reverse() && out.join('');
		if (num.length === 2) out += '.' + num[1];
		if(out[0] == '-'){
			out = out.replace(',','');
		}
		return out;
	};
	
	formatCurrencyInterger = function(value) {
		if(value < 0) {
			var valuetmp = Math.abs(value);
			var valuetest = '-'+ formatCurrency(valuetmp);
			return valuetest;
		}
		else {
			return formatCurrency(value);
		}
	};
	formatCurrencyNegativeToInteger = function(value) {
		if(value < 0) {
			var valuetmp = Math.abs(value);
			var valuetest = formatCurrency(valuetmp);
			return valuetest;
		}
		else {
			return formatCurrency(value);
		}
	};
	
	formatCurrencyFor = function(idInput) {
		if(typeof idInput === 'string') {
			idInput = $('#'+idInput);
		}
		idInput.bind('keyup', function(e) {
			var valMoneyInput = idInput.val();
			valMoneyInput = returnMoneyValue(valMoneyInput);
			if(isNaN(valMoneyInput) || valMoneyInput == "" || valMoneyInput == '') {
				return false;
			}
			var _valMoneyInput = formatCurrency(valMoneyInput);
			idInput.val(_valMoneyInput);
		});
		idInput.bind('paste', function(){
		    var tm = setTimeout(function(){
		    	var valMoneyInput = idInput.val();
		        valMoneyInput = returnMoneyValue(valMoneyInput);
		        if(isNaN(valMoneyInput) || valMoneyInput == "" || valMoneyInput == '') {
		        	return false;
		        }
		        var _valMoneyInput = formatCurrency(valMoneyInput);
		        idInput.val(_valMoneyInput); 
		        	clearTimeout(tm);
		    },200);
		});
	};
	
	maskDate = function(selector){
		if(typeof selector === 'string') {
			selector = $('#'+selector);
		}
		selector.mask("99/99/9999");
	};
	maskMonth = function(selector){
		if(typeof selector === 'string') {
			selector = $('#'+selector);
		}
		selector.mask("99/9999");
	};
	
	applyDateTimePicker = function(selector) {
		if(typeof selector === 'string') {
			selector = $('#'+selector);
		}
		
		var opts = {};
		try {
			var dataOptions = selector.attr('data-options');
			if(dataOptions != null && dataOptions != '') {
				var __opts = JSON.stringify(eval("({" + dataOptions + "})"));
				opts = JSON.parse(__opts);
			}
		} catch (e) {
			
		}
		var dateFormat = opts.dateFormat;
		var hideYear = opts.hideYear;
		var memuMonthShow = opts.memuMonthShow;
		var menuYearShow = opts.menuYearShow;
		var yearRangeFlag = opts.yearRangeFlag;
		var showFocus = opts.showFocus;
		var timeShow = opts.timeShow;
		var yearRangeFuture = opts.yearRangeFuture;
		var monthYearShow = opts.monthYearShow;
		var onlyMonthCurrent = opts.onlyMonthCurrent;
		
		var format = "dd/mm/yy";
		if (dateFormat != undefined && dateFormat != null) {
			format = dateFormat;		
		}
		if(monthYearShow != undefined && monthYearShow != null){
			maskMonth(selector);
		}else{
			maskDate(selector);
		}
		var menuMonth = false;
		if (memuMonthShow != undefined && memuMonthShow != null) {
			menuMonth = memuMonthShow;
		}
		var menuYear = false;
		if (menuYearShow != undefined && menuYearShow != null) {
			menuYear = menuYearShow;
		}
		var minDate = null;
		var maxDate = null;
		if (hideYear != undefined && hideYear != null && hideYear == true) {
			minDate = new Date(2012, 0, 1);
			maxDate = new Date(2012, 11, 31);
		}
		var yearRange = null;
		if (yearRangeFlag != null && yearRangeFlag != undefined) {
			var now = new Date();
			var t = now.getFullYear();
			var f = t -100;
			if(yearRangeFuture != null && yearRangeFuture != undefined){
				t = t + 100;
				yearRange = f+":"+t;
			} else{
				yearRange = f+":"+t;
			}
			
			
		}
		var showOn = 'button';
		if (showFocus != undefined && showFocus != null && showFocus == true) {
			showOn = 'focus';
		}
		if (!timeShow)
		{
			selector.datepicker(
				{
					monthNames: ["Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"],
					monthNamesShort: ["Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"],
					dayNamesMin: ["CN", "T2", "T3", "T4", "T5", "T6", "T7"],
					showOn: showOn,
					dateFormat: format,
					buttonImage: '/resources/images/icon_calendar.jpg',
					buttonImageOnly: true,
					changeMonth: menuMonth,
					changeYear: menuYear,
					minDate: minDate,
					maxDate: maxDate,
					buttonText: '',
					useThisTheme: 'start',
					yearRange: yearRange,
					create: function(event, ui) {
					},
					onClose: function(dateText, inst) {
					},
					beforeShow: function(input, inst) {
						setTimeout(function() {
							$('.ui-datepicker-month').css('width', '60%');
							$('#ui-datepicker-div').css('z-index', 1000000);
						}, 1);
						if ((hideYear != null && hideYear == true)||(onlyMonthCurrent != null && onlyMonthCurrent == true)) {
							setTimeout(function() {
								$('.ui-datepicker-next').hide();
								$('.ui-datepicker-prev').hide();
								$('.ui-datepicker-year').hide();
							}, 1);
						}
					},
					onChangeMonthYear: function(year, month, inst) {
						setTimeout(function() {
							$('.ui-datepicker-month').css('width', '60%');
						}, 1);
						if ((hideYear != null && hideYear == true)||(onlyMonthCurrent != null && onlyMonthCurrent == true)) {
							setTimeout(function() {
								$('.ui-datepicker-next').hide();
								$('.ui-datepicker-prev').hide();
								$('.ui-datepicker-year').hide();
							}, 1);
						}
					}
				}
			);
		}
	};
	
	$(document).ready(function(){
		$('.vinput-number').each(function() {
			bindFormatOnTextfield($(this), _TF_NUMBER);
		});
		
		$('.vinput-number-comma').each(function() {
			bindFormatOnTextfield($(this), _TF_NUMBER_COMMA);
		});
		
		$('.vinput-number-dot').each(function() {
			bindFormatOnTextfield($(this), _TF_NUMBER_DOT);
		});
		
		$('.vinput-number-sign').each(function() {
			bindFormatOnTextfield($(this), _TF_NUMBER_SIGN);
		});
		
		$('.vinput-number-convfact').each(function() {
			bindFormatOnTextfield($(this), _TF_NUMBER_CONVFACT);
		});
		
		$('.vinput-money').each(function() {
			bindFormatOnTextfield($(this), _TF_NUMBER_COMMA);
			formatCurrencyFor($(this));
		});
		
		$('.vinput-date').each(function() {
			applyDateTimePicker($(this));
		});
	});
	
	return {
		_TF_A_Z : _TF_A_Z,
		_TF_NUMBER : _TF_NUMBER,
		_TF_NUMBER_DOT : _TF_NUMBER_DOT,
		_TF_NUMBER_COMMA : _TF_NUMBER_COMMA,
		_TF_NUMBER_SIGN : _TF_NUMBER_SIGN,
		_TF_NUMBER_CONVFACT : _TF_NUMBER_CONVFACT,
		bindFormatOnTextfield:bindFormatOnTextfield,
		applyDateTimePicker:applyDateTimePicker
	};
})($);

function Map() {
    this.keyArray = new Array(); // Keys
    this.valArray = new Array(); // Values
    this.put = put;
    this.get = get;
    this.size = size;  
    this.clear = clear;
    this.keySet = keySet;
    this.valSet = valSet;
    this.showMe = showMe;   // returns a string with all keys and values in map.
    this.findIt = findIt;
    this.remove = remove;	
    this.findIt4Val = findIt4Val;
	function put(key, val) {
    	var elementIndex = this.findIt(key);
	    if(elementIndex == (-1)) {
	        this.keyArray.push(key);
	        this.valArray.push(val);
	    } else {
	        this.valArray[elementIndex] = val;
	    }
	}
	function get(key) {
	    var result = null;
	    var elementIndex = this.findIt(key);
	    if (elementIndex != (-1)) {
	        result = this.valArray[elementIndex];
	    }
	    return result;
	}	
	function remove(key) {
	    var result = null;
	    var elementIndex = this.findIt(key);
	    if(elementIndex != (-1)) {
	        // this.keyArray = this.keyArray.myRemoveAt(elementIndex);
	    	this.keyArray.splice(elementIndex,1);
	        // this.valArray = this.valArray.myRemoveAt(elementIndex);
	    	this.valArray.splice(elementIndex,1);
	    }  
	    return ;
	}
	function size() {
	    return (this.keyArray.length);
	}
	function clear() {
        this.keyArray = new Array();
		this.valArray = new Array();
	}
	function keySet() {
	    return (this.keyArray);
	}
	function valSet() {
	    return (this.valArray);
	}
	function showMe() {
	    var result = "";
	    for( var i = 0; i < this.keyArray.length; i++ ) {
	        result += "Key: " + this.keyArray[ i ] + "\tValues: " + this.valArray[ i ] + "\n";
	    }
	    return result;
	}
	function findIt(key) {
	    var result = (-1);
	    for(var i = 0; i < this.keyArray.length; i++) {
	        if(this.keyArray[ i ] == key) {
	            result = i;
	            break;
	        }
	    }
	    return result;
	}
	function findIt4Val(val){
		var result = (-1);
	    for(var i = 0; i < this.valArray.length; i++) {
	        if(this.valArray[ i ] == val) {
	            result = i;
	            break;
	        }
	    }
	    return result; 
	}
}
VTCommonJS = (function($) {
	var mapId = null;
	var ENTER = 13;
	var isNullOrEmpty = function(value) {
		if(value == null || value == undefined || value == '') {
			return true;
		} else {
			return false;
		}
	};
	/**
		VTCommonJS.showDialogSearch2({
		    inputs : [
		        {id:'code', maxlength:50, label:'Mã KH'},
		        {id:'name', maxlength:250, label:'Tên KH'},
		        {id:'address', maxlength:250, label:'Địa chỉ', width:410}
		    ],
		    url : '/commons/customer-in-shop/search',
		    columns : [[
		        {field:'customerCode', title:'Mã KH', align:'left', width: 110, sortable:false, resizable:false},
		        {field:'customerName', title:'Tên KH', align:'left', width: 150, sortable:false, resizable:false},
		        {field:'address', title:'Địa chỉ', align:'left', width: 170, sortable:false, resizable:false},
		        {field:'choose', title:'', align:'center', width:40, sortable:false, resizable:false, formatter:function(value,row,index) {
		            return '<a href="javascript:void(0)" onclick="">chọn</a>';         
		        }}
		    ]]
		});
	 * 
	 */
	var showDialogSearch2 = function(opts) {
		var inputs = opts.inputs;
		var url = opts.url;
		var searchCallback = opts.searchCallback;
		var columns = opts.columns;
		var dialogInfo = opts.dialogInfo;
		var params = opts.params;
		var html = '<div id="common-dialog-search-2-textbox" class="easyui-dialog">';
		html += '<div class="PopupContentMid">';
		html += '<div class="GeneralForm Search1Form" >';
		for(var i = 0; i < inputs.length; i++) {
			html += '<label id="label-'+inputs[i].id+'" class="LabelStyle Label1Style" style=" width: 100px;">'+inputs[i].label+'</label>';
			html += '<input id="'+inputs[i].id+'" maxlength="'+(isNullOrEmpty(inputs[i].maxlength) ? 250 : inputs[i].maxlength)+'" tabindex="'+i+1+'" type="text" style="width: '+(isNullOrEmpty(inputs[i].width) ? 145 : inputs[i].width)+'px;" value="'+(isNullOrEmpty(inputs[i].value) ? "" : inputs[i].value)+'" class="InputTextStyle InputText1Style"/>';
			if((i+1) % 2 ==0) {
				html += '<div class="Clear"></div>';
			}
		}
		html += '<div class="Clear"></div>'; 
		html += '<div class="BtnCenterSection">';
		html += '<button class="BtnGeneralStyle BtnGeneralMStyle" id="common-dialog-button-search">Tìm kiếm</button>';
		html += '</div>';
		html += '<div class="Clear"></div>';
		html += '<div class="GridSection" id="common-dialog-grid-container">';
		html += '<table id="common-dialog-grid-search"></table>';
		html += '</div>';
		html += '<div class="BtnCenterSection">';
		html += '<button class="BtnGeneralStyle BtnGeneralMStyle" onclick="$(\'#common-dialog-search-2-textbox\').dialog(\'close\');">Đóng</button>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		
		$('body').append(html);
		
		$('#common-dialog-search-2-textbox').dialog({
			title: (dialogInfo != null && dialogInfo != undefined && dialogInfo.title != null && dialogInfo.title != undefined) ? dialogInfo.title : 'Thông tin tìm kiếm',
			width: (dialogInfo != null && dialogInfo != undefined && dialogInfo.width != null && dialogInfo.width != undefined) ? dialogInfo.width : 600, 
			height: (dialogInfo != null && dialogInfo != undefined && dialogInfo.height != null && dialogInfo.height != undefined) ? dialogInfo.width : 'auto',
			closed: false,
			cache: false,
			modal: true,
			onOpen: function() {
				for(var i = 0; i < inputs.length; i++) {
					if(inputs[i].type != null && inputs[i].type != undefined && inputs[i].type == 'date') {
						VTUtilJS.applyDateTimePicker($('#common-dialog-search-2-textbox #'+inputs[i].id));
					}
				}
				
				$('#common-dialog-search-2-textbox #common-dialog-button-search').unbind('click');
				$('#common-dialog-search-2-textbox #common-dialog-button-search').bind('click', function() {
					if(searchCallback != null && searchCallback != undefined) {
						searchCallback.call(this);
					} else {
						$('#common-dialog-grid-search').datagrid('reload');
					}
				});
				$('#common-dialog-search-2-textbox input').unbind('keyup');
				$('#common-dialog-search-2-textbox input').bind('keyup', function(e) {	
					if(e.keyCode == ENTER) {
						$('#common-dialog-search-2-textbox #common-dialog-button-search').click();
					}
				});
				$('#common-dialog-grid-search').datagrid({
					url : url,
					autoRowHeight : true,
					rownumbers : true,
					checkOnSelect :true,
					method: 'GET',
					pagination:true,
					rowNum : 10,
					pageSize:10,
					scrollbarSize : 0,
					singleSelect:true,
					pageNumber:1,
					queryParams:{
						page:1
					},
					onBeforeLoad: function(param) {
						if(searchCallback == null || searchCallback == undefined) {
							if(params != null && params != undefined) {
								var keys = Object.keys(params);
								for(var i = 0; i < keys.length; i++) {
									param[keys[i]] = params[keys[i]];
								}
							}
							for(var i = 0; i < inputs.length; i++) {
								param[inputs[i].id] = $('#common-dialog-search-2-textbox #'+inputs[i].id).val();
							}
							param = $.param(param, true);
						}
					},
					fitColumns:true,
					width : ($('#common-dialog-search-2-textbox').width() - 40),
					columns:columns,
					onLoadSuccess :function(){
						$('#common-dialog-search-2-textbox .datagrid-header-rownumber').html('STT');
						var dHeight = $('#common-dialog-search-2-textbox').height();
						var wHeight = $(window).height();
						var top = (wHeight - dHeight) / 2 > 180 ? (wHeight - dHeight) / 2 - 180 : (wHeight - dHeight) / 2;
						$('#common-dialog-search-2-textbox').dialog('move', {top : top});
					}
				});
			},
			onClose: function() {
				$('#common-dialog-search-2-textbox').remove(); 
			}
		});
	};
  	
	/**
	 * 
		VTCommonJS.showDialogSearch2WithCheckbox({
		    inputs : [
		        {id:'code', maxlength:50, label:'Mã KH'},
		        {id:'name', maxlength:250, label:'Tên KH'},
		        {id:'address', maxlength:250, label:'Địa chỉ', width:410}
		    ],
		    chooseCallback : function(listId) {
		        console.log(listId);
		    },
		    url : '/commons/customer-in-shop/search',
		    columns : [[
		        {field:'customerCode', title:'Mã KH', align:'left', width: 110, sortable:false, resizable:false},
		        {field:'customerName', title:'Tên KH', align:'left', width: 150, sortable:false, resizable:false},
		        {field:'address', title:'Địa chỉ', align:'left', width: 170, sortable:false, resizable:false},
		        {field:'cb', checkbox:true, align:'center', width:80,sortable : false,resizable : false},
		    ]]
		});
	 * 
	 */
	var showDialogSearch2WithCheckbox = function(opts) {
		var inputs = opts.inputs;
		var url = opts.url;
		var searchCallback = opts.searchCallback;
		var chooseCallback = opts.chooseCallback;
		var columns = opts.columns;
		var dialogInfo = opts.dialogInfo;
		var params = opts.params;
		var html = '<div id="common-dialog-search-2-textbox" class="easyui-dialog">';
		html += '<div class="PopupContentMid">';
		html += '<div class="GeneralForm Search1Form" >';
		for(var i = 0; i < inputs.length; i++) {
			html += '<label id="label-'+inputs[i].id+'" class="LabelStyle Label1Style" style=" width: 100px;">'+inputs[i].label+'</label>';
			html += '<input id="'+inputs[i].id+'" maxlength="'+(isNullOrEmpty(inputs[i].maxlength) ? 250 : inputs[i].maxlength)+'" tabindex="'+i+1+'" type="text" style="width: '+(isNullOrEmpty(inputs[i].width) ? 145 : inputs[i].width)+'px;" value="'+(isNullOrEmpty(inputs[i].value) ? "" : inputs[i].value)+'" class="InputTextStyle InputText1Style"/>';
			if((i+1) % 2 ==0) {
				html += '<div class="Clear"></div>';
			}
		}
		html += '<div class="Clear"></div>'; 
		html += '<div class="BtnCenterSection">';
		html += '<button class="BtnGeneralStyle BtnGeneralMStyle" id="common-dialog-button-search">Tìm kiếm</button>';
		html += '</div>';
		html += '<div class="Clear"></div>';
		html += '<div class="GridSection" id="common-dialog-grid-container">';
		html += '<table id="common-dialog-grid-search"></table>';
		html += '</div>';
		html += '<div class="BtnCenterSection">';
		html += '<button id="common-dialog-button-save" class="BtnGeneralStyle">Chọn</button>';
		html += '<button class="BtnGeneralStyle BtnGeneralMStyle" onclick="$(\'#common-dialog-search-2-textbox\').dialog(\'close\');">Đóng</button>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		
		$('body').append(html);
		
		$('#common-dialog-search-2-textbox').dialog({
			title: (dialogInfo != null && dialogInfo != undefined && dialogInfo.title != null && dialogInfo.title != undefined) ? dialogInfo.title : 'Thông tin tìm kiếm',
			width: (dialogInfo != null && dialogInfo != undefined && dialogInfo.width != null && dialogInfo.width != undefined) ? dialogInfo.width : 600, 
			height: (dialogInfo != null && dialogInfo != undefined && dialogInfo.height != null && dialogInfo.height != undefined) ? dialogInfo.width : 'auto',
			closed: false,
			cache: false,
			modal: true,
			onOpen: function() {
				for(var i = 0; i < inputs.length; i++) {
					if(inputs[i].type != null && inputs[i].type != undefined && inputs[i].type == 'date') {
						VTUtilJS.applyDateTimePicker($('#common-dialog-search-2-textbox #'+inputs[i].id));
					}
				}
				
				$('#common-dialog-search-2-textbox #common-dialog-button-search').unbind('click');
				$('#common-dialog-search-2-textbox #common-dialog-button-search').bind('click', function() {
					if(searchCallback != null && searchCallback != undefined) {
						searchCallback.call(this);
					} else {
						$('#common-dialog-grid-search').datagrid('reload');
					}
				});
				$('#common-dialog-search-2-textbox input').unbind('keyup');
				$('#common-dialog-search-2-textbox input').bind('keyup', function(e) {	
					if(e.keyCode == ENTER) {
						$('#common-dialog-search-2-textbox #common-dialog-button-search').click();
					}
				});
				$('#common-dialog-search-2-textbox #common-dialog-button-save').unbind('click');
				$('#common-dialog-search-2-textbox #common-dialog-button-save').bind('click', function() {
					if(chooseCallback != null && chooseCallback != undefined) {
						chooseCallback.call(this, mapId.valArray);
					}
				});
				mapId = new Map();
				$('#common-dialog-grid-search').datagrid({
					url : url,
					method : 'GET',
					autoRowHeight : true,
					rownumbers : true,
					checkOnSelect :true,
					pagination:true,
					rowNum : 10,
					pageSize : 10,
					scrollbarSize : 0,
					pageNumber:1,
					queryParams : {
						page:1
					},
					onBeforeLoad : function(param) {
						if(searchCallback == null || searchCallback == undefined) {
							if(params != null && params != undefined) {
								var keys = Object.keys(params);
								for(var i = 0; i < keys.length; i++) {
									param[keys[i]] = params[keys[i]];
								}
							}
							for(var i = 0; i < inputs.length; i++) {
								param[inputs[i].id] = $('#common-dialog-search-2-textbox #'+inputs[i].id).val();
							}
							param = $.param(param, true);
						}
					},
					fitColumns:true,
					width : ($('#common-dialog-search-2-textbox').width() - 40),
					columns:columns,
					onCheck:function(idx,row){
						var __keys = Object.keys(row);
						var idName = 'id';
						for(var i = 0; i < __keys.length; i++) {
							if(__keys[i].toLowerCase().indexOf('id') != -1) {
								idName = __keys[i];
								break;
							}
						}
						mapId.put(row[idName], row);
					},
					onUncheck:function(idx,row){
						var __keys = Object.keys(row);
						var idName = 'id';
						for(var i = 0; i < __keys.length; i++) {
							if(__keys[i].toLowerCase().indexOf('id') != -1) {
								idName = __keys[i];
								break;
							}
						}
						mapId.remove(row[idName]);
					},
					onCheckAll:function(rows){
						if(rows.length == 0) {
							 return;
						}
						var __keys = Object.keys(rows[0]);
						var idName = 'id';
						for(var i = 0; i < __keys.length; i++) {
							if(__keys[i].toLowerCase().indexOf('id') != -1) {
								idName = __keys[i];
								break;
							}
						}
						for(var i = 0; i < rows.length; i++) {
							var row = rows[i];
							mapId.put(row[idName], row);
						}
					},
					onUncheckAll:function(rows){
						if(rows.length == 0) {
							 return;
						}
						var __keys = Object.keys(rows[0]);
						var idName = 'id';
						for(var i = 0; i < __keys.length; i++) {
							if(__keys[i].toLowerCase().indexOf('id') != -1) {
								idName = __keys[i];
								break;
							}
						}
						for(var i = 0; i < rows.length; i++) {
							var row = rows[i];
							mapId.remove(row[idName]);
						}
					},
					onLoadSuccess :function(data){
						if(($.isArray(data) && data.length != 0) || (data.rows != null && data.rows != undefined && $.isArray(data.rows) && data.rows.length != 0)) {
							var __keys = (data.rows == null || data.rows == undefined) ? Object.keys(data[0]) : Object.keys(data.rows[0]);
							var rows = (data.rows == null || data.rows == undefined) ? data : data.rows;
							var idName = 'id';
							for(var i = 0; i < __keys.length; i++) {
								if(__keys[i].toLowerCase().indexOf('id') != -1) {
									idName = __keys[i];
									break;
								}
							}
							var isCheckAll=true;
							for(var i = 0; i < rows.length; i++) {
								if(mapId.get(rows[i][idName])) {
									$('#common-dialog-grid-search').datagrid('checkRow', i);
								} else {
									 isCheckAll = false;
								}
							}
							if(isCheckAll) {
								$('#common-dialog-search-2-textbox .datagrid-header-row input[type=checkbox]').attr('checked', 'checked');
							}
						}
						
						$('#common-dialog-search-2-textbox .datagrid-header-rownumber').html('STT');
						var dHeight = $('#common-dialog-search-2-textbox').height();
						var wHeight = $(window).height();
						var top = (wHeight - dHeight) / 2 > 180 ? (wHeight - dHeight) / 2 - 180 : (wHeight - dHeight) / 2;
						$('#common-dialog-search-2-textbox').dialog('move', {top : top});
					}
				});
			},
			onClose: function() {
				$('#common-dialog-search-2-textbox').remove(); 
			}
		});
	};
	
	/*
	 	VTCommonJS.showDialogSearchTree({
		    inputs : [
		        {id:'code', maxlength:50, label:'Mã SP'},
		        {id:'name', maxlength:250, label:'Tên SP'}
		    ],
		    url : 'http://localhost:8080/rest/catalog/group-po/tree/2.json',
		    chooseCallback : function(node) {
		        console.log(node);
		    },
		    searchCallback : null,
		    dialogInfo : null,
		    params : {
    		    id : 214
		    }
		});
	 * inputs : field dùng để định nghĩa các input search. nếu fieldColumns ko dc định nghĩa thì grid sẽ hiển thị dựa trên field này.
	 * dữ liệu đẩy lên server cũng có những field này.
	 * url : url để request đến server
	 * chooseCallback : callback khi chọn item
	 * searchCallback : nếu có hàm này thì sẽ gọi hàm này để search. nếu ko thì sẽ reload lại datagrid dựa trên những input field
	 * dialogInfo : một số thông tin thêm ví dụ như dialogInfo.title hay dialogInfo.width hay dialogInfo.height
	 * 
	 */
	var showDialogSearchTree  = function(opts) {
		var inputs = opts.inputs;
		var url = opts.url;
		var chooseCallback = opts.chooseCallback;
		var searchCallback = opts.searchCallback;
		var dialogInfo = opts.dialogInfo;
		var params = opts.params;
		var html = '<div id="common-dialog-search-tree" class="easyui-dialog">';
		html += '<div class="PopupContentMid2">';
		html += '<div class="GeneralForm Search1Form">';
		//html += '<h2 class="Title2Style">Thông tin tìm kiếm<img style="display:none;" id="loadingDialog" src="/resources/scripts/plugins/jquery-easyui-1.3.2/themes/default/images/loading.gif"></h2>';
		for(var i = 0; i < inputs.length; i++) {
			html += '<label id="label-'+inputs[i].id+'" class="LabelStyle Label1Style" style=" width: 100px;">'+inputs[i].label+'</label>';
			html += '<input id="'+inputs[i].id+'" maxlength="'+(isNullOrEmpty(inputs[i].maxlength) ? 250 : inputs[i].maxlength)+'" tabindex="'+i+1+'" type="text" style="width: '+(isNullOrEmpty(inputs[i].width) ? 145 : inputs[i].width)+'px;" value="'+(isNullOrEmpty(inputs[i].value) ? "" : inputs[i].value)+'" class="InputTextStyle InputText1Style"/>';
			if((i+1) % 2 ==0) {
				html += '<div class="Clear"></div>';
			}
		}
		html += '<div class="Clear"></div>';
		html += '<div class="BtnCenterSection">';
		html += '<button id="common-dialog-button-search" class="BtnGeneralStyle">Tìm kiếm</button>';
		html += '</div>';
		html += '<div class="Clear"></div>';
		html += '</div>';
		html += '<div class="GeneralForm Search1Form">';
		html += '<h2 class="Title2Style Title2MTStyle">Kết quả tìm kiếm</h2>';
		html += '<div  style="max-height:250px;overflow:auto;">';
		html += '<div class="ReportTreeSection" >';
		html += '<ul id="common-dialog-tree"></ul>';
		html += '</div>';
		html += '</div>';
		html += '<div class="Clear"></div>';
		html += '<div class="BtnCenterSection">';
		html += '<button class="BtnGeneralStyle" onclick="$(\'#common-dialog-search-tree\').dialog(\'close\');">Đóng</button>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		
		$('body').append(html);
		
		$('#common-dialog-search-tree').dialog({
			title: (dialogInfo != null && dialogInfo != undefined && dialogInfo.title != null && dialogInfo.title != undefined) ? dialogInfo.title : 'Thông tin tìm kiếm',
			width: (dialogInfo != null && dialogInfo != undefined && dialogInfo.width != null && dialogInfo.width != undefined) ? dialogInfo.width : 600, 
			height: (dialogInfo != null && dialogInfo != undefined && dialogInfo.height != null && dialogInfo.height != undefined) ? dialogInfo.height : 'auto',
			closed: false,  
			cache: false,
			modal: true,
			position: 'middle',
			center: true, 
			onOpen: function(){
				for(var i = 0; i < inputs.length; i++) {
					if(inputs[i].type != null && inputs[i].type != undefined && inputs[i].type == 'date') {
						VTUtilJS.applyDateTimePicker($('#common-dialog-search-tree #'+inputs[i].id));
					}
				}
				
				$('#common-dialog-search-tree #common-dialog-button-search').unbind('click');
				$('#common-dialog-search-tree #common-dialog-button-search').bind('click', function() {
				if(searchCallback != null && searchCallback != undefined) {
						searchCallback.call(this);
					} else {
						$('#common-dialog-tree').tree('reload');
					}
				});
				$('#common-dialog-tree').tree({
	        		url : url,
	        		method : 'GET',
	        		animate: true,
	        		onBeforeLoad:function(node,param){
	        			if(searchCallback == null || searchCallback == undefined) {
	        				if(params != null && params != undefined) {
								 var keys = Object.keys(params);
								 for(var i = 0; i < keys.length; i++) {
									 param[keys[i]] = params[keys[i]];
								 }
		        			}
							for(var i = 0; i < inputs.length; i++) {
								param[inputs[i].id] = $('#common-dialog-search-tree #'+inputs[i].id).val();
							}
							param = $.param(param, true);
	        			}
	        		},
	        		onSelect:function(node) {
	        			if(chooseCallback != null && chooseCallback != undefined) {
	        				chooseCallback.call(this, node);
	        			}
	        		},
	        		onLoadSuccess:function(node,data){
	        			
	        		}
	        	});
	        },
	        onClose : function(){
	        	VTCommonJS.chooseCallback = null;
				$('#common-dialog-search-tree').remove();
	        }
		});
	};
	
	var listNodeChoose = null;
	/*
	 	VTCommonJS.showDialogSearchTreeWithCheckbox({
		    inputs : [
		        {id:'code', maxlength:50, label:'Mã SP'},
		        {id:'name', maxlength:250, label:'Tên SP'}
		    ],
		    url : 'http://localhost:8080/rest/catalog/group-po/tree/2.json',
		    chooseCallback : function(node) {
		        console.log(node);
		    },
		    searchCallback : null,
		    dialogInfo : null,
		    params : {
    		    id : 214
		    }
		});	
	
	 * inputs : inputs dùng để định nghĩa các input search. nếu fieldColumns ko dc định nghĩa thì grid sẽ hiển thị dựa trên field này.
	 * dữ liệu đẩy lên server cũng có những field này.
	 * url : url để request đến server
	 * chooseCallback : callback khi chọn item
	 * searchCallback : nếu có hàm này thì sẽ gọi hàm này để search. nếu ko thì sẽ reload lại datagrid dựa trên những input field
	 * dialogInfo : một số thông tin thêm ví dụ như dialogInfo.title hay dialogInfo.width hay dialogInfo.height
	 * 
	 */
	var showDialogSearchTreeWithCheckbox  = function(opts) {
		var inputs = opts.inputs;
		var url = opts.url;
		var chooseCallback = opts.chooseCallback;
		var searchCallback = opts.searchCallback;
		var dialogInfo = opts.dialogInfo;
		var params = opts.params;
		var html = '<div id="common-dialog-search-tree" class="easyui-dialog">';
		html += '<div class="PopupContentMid2">';
		html += '<div class="GeneralForm Search1Form">';
		//html += '<h2 class="Title2Style">Thông tin tìm kiếm<img style="display:none;" id="loadingDialog" src="/resources/scripts/plugins/jquery-easyui-1.3.2/themes/default/images/loading.gif"></h2>';
		for(var i = 0; i < inputs.length; i++) {
			html += '<label id="label-'+inputs[i].id+'" class="LabelStyle Label1Style" style=" width: 100px;">'+inputs[i].label+'</label>';
			html += '<input id="'+inputs[i].id+'" maxlength="'+(isNullOrEmpty(inputs[i].maxlength) ? 250 : inputs[i].maxlength)+'" tabindex="'+i+1+'" type="text" style="width: '+(isNullOrEmpty(inputs[i].width) ? 145 : inputs[i].width)+'px;" value="'+(isNullOrEmpty(inputs[i].value) ? "" : inputs[i].value)+'" class="InputTextStyle InputText1Style"/>';
			if((i+1) % 2 ==0) {
				html += '<div class="Clear"></div>';
			}
		}
		html += '<div class="Clear"></div>';
		html += '<div class="BtnCenterSection">';
		html += '<button id="common-dialog-button-search" class="BtnGeneralStyle">Tìm kiếm</button>';
		html += '</div>';
		html += '<div class="Clear"></div>';
		html += '</div>';
		html += '<div class="GeneralForm Search1Form">';
		html += '<h2 class="Title2Style Title2MTStyle">Kết quả tìm kiếm</h2>';
		html += '<div  style="max-height:250px;overflow:auto;">';
		html += '<div class="ReportTreeSection" >';
		html += '<ul id="common-dialog-tree"></ul>';
		html += '</div>';
		html += '</div>';
		html += '<div class="Clear"></div>';
		html += '<div class="BtnCenterSection">';
		html += '<button id ="common-dialog-button-choose" class="BtnGeneralStyle BtnGeneralMStyle">Chọn</button>';
		html += '<button class="BtnGeneralStyle BtnGeneralMStyle" onclick="$(\'#common-dialog-search-tree\').dialog(\'close\');">Đóng</button>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		
		$('body').append(html);
		
		$('#common-dialog-search-tree').dialog({
			title: (dialogInfo != null && dialogInfo != undefined && dialogInfo.title != null && dialogInfo.title != undefined) ? dialogInfo.title : 'Thông tin tìm kiếm',
			width: (dialogInfo != null && dialogInfo != undefined && dialogInfo.width != null && dialogInfo.width != undefined) ? dialogInfo.width : 600, 
			height: (dialogInfo != null && dialogInfo != undefined && dialogInfo.height != null && dialogInfo.height != undefined) ? dialogInfo.height : 'auto',
			closed: false,  
			cache: false,
			modal: true,
			position: 'middle',
			center: true, 
			onOpen: function(){
				for(var i = 0; i < inputs.length; i++) {
					if(inputs[i].type != null && inputs[i].type != undefined && inputs[i].type == 'date') {
						VTUtilJS.applyDateTimePicker($('#common-dialog-search-tree #'+inputs[i].id));
					}
				}
				
				$('#common-dialog-search-tree #common-dialog-button-search').unbind('click');
				$('#common-dialog-search-tree #common-dialog-button-search').bind('click', function() {
					if(searchCallback != null && searchCallback != undefined) {
						searchCallback.call(this);
					} else {
						$('#common-dialog-tree').tree('reload');
					}
				});
				$('#common-dialog-search-tree #common-dialog-button-choose').unbind('click');
				$('#common-dialog-search-tree #common-dialog-button-choose').bind('click', function() {
					if(chooseCallback != null && chooseCallback != undefined) {
						chooseCallback.call(this, listNodeChoose);
					}
					$('#common-dialog-search-tree').dialog('close');
				});
				listNodeChoose = new Map();
				$('#common-dialog-tree').tree({
	        		url : url,
	        		method : 'GET',
	        		animate: true,
	        		checkbox : true,
	        		cascadeCheck : true,
	        		onBeforeLoad:function(node,param){
	        			if(searchCallback == null || searchCallback == undefined) {
	        				if(params != null && params != undefined) {
								 var keys = Object.keys(params);
								 for(var i = 0; i < keys.length; i++) {
									 param[keys[i]] = params[keys[i]];
								 }
		        			}
							for(var i = 0; i < inputs.length; i++) {
								param[inputs[i].id] = $('#common-dialog-search-tree #'+inputs[i].id).val();
							}
							param = $.param(param, true);
	        			}
	        		},
	        		onCheck : function(node, checked) {
        				var __keys = Object.keys(node);
						var idName = 'id';
						for(var i = 0; i < __keys.length; i++) {
							if(__keys[i].toLowerCase().indexOf('id') != -1) {
								idName = __keys[i];
								break;
							}
						}
						if(checked) {
							//listNodeChoose.put(node[idName], node);
							var nodes = $('#common-dialog-search-tree #common-dialog-tree').tree('getChecked');
							for(var i = 0; i < nodes.length; i++) {
								var n = nodes[i];
								listNodeChoose.put(n[idName], n);
							}
						} else {
							//listNodeChoose.remove(node[idName]);
							var nodes = $('#common-dialog-search-tree #common-dialog-tree').tree('getChecked', 'unchecked');
							for(var i = 0; i < nodes.length; i++) {
								var n = nodes[i];
								listNodeChoose.remove(n[idName]);
							}
						}
	        		},
	        		onLoadSuccess:function(node,data){
	        			var arr  = listNodeChoose.keyArray;
	                	if(arr.length > 0){
	                		for(var i = 0;i < arr.length; i++){
	                			var n = $('#common-dialog-tree').tree('find', arr[i]);
	                			if(n != null){
	                				$('#common-dialog-tree').tree('check',n.target);
	                			}
	                		}
	                	}
	        		}
	        	});
	        },
	        onClose : function(){
	        	VTCommonJS.chooseCallback = null;
				$('#common-dialog-search-tree').remove();
	        }
		});
	};
	
	return {
		showDialogSearchTree : showDialogSearchTree,
		showDialogSearchTreeWithCheckbox : showDialogSearchTreeWithCheckbox,
		showDialogSearch2 : showDialogSearch2,
		showDialogSearch2WithCheckbox : showDialogSearch2WithCheckbox
	};
})($);